package com.zhongkai.service.impl;

import com.mysql.jdbc.StringUtils;
import com.zhongkai.Bean.*;
import com.zhongkai.StringStatic;
import com.zhongkai.app.service.BigDateService;
import com.zhongkai.app.service.DeviceOperationService;
import com.zhongkai.app.service.IBaseDao;
import com.zhongkai.app.service.PageQuerDao;
import com.zhongkai.jedis.JedisClient;
import com.zhongkai.model.utils.ZhongkaiResult;
import com.zhongkai.model3.Province;
import com.zhongkai.model3.SetUnit;
import com.zhongkai.model3.Unlike;
import org.codehaus.jackson.map.ObjectMapper;
import org.hibernate.criterion.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * 大数据监控
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class BigDateServiceImpl implements BigDateService {

    @Autowired
    private IBaseDao iBaseDao;

    @Autowired
    private PageQuerDao pageQuerDao;


    @Autowired
    private JedisClient jedisClient;
/*    @Autowired
    private RedisUtils redisUtils;*/

    @Autowired
    private DeviceOperationService deviceOperationService;
    /**
     * 状态监控
     *
     * @param page 当前页数
     * @param rows 每页数据条数
     */
    @Override
    public ZhongkaiResult getUnitBigDate(Integer page, Integer rows) throws IOException {
        if (page == 0 || rows == 0) {
            return ZhongkaiResult.build(400, "数据不完整");
        }

        PageBean pageBean = new PageBean();
        pageBean.setCurrentPage(page);
        pageBean.setPageSize(rows);

/*        Collection collection = new ArrayList();

        ((ArrayList) collection).add(100);*/


        DetachedCriteria detachedCriteria = DetachedCriteria.forClass(SetUnit.class);
        detachedCriteria.add(Restrictions.eq("setRemove", "1")); //增加条件
        detachedCriteria.add(Restrictions.eq("setBound", "2")); //增加条件 是否绑定业主  1 未绑定 2 已绑定
        //   detachedCriteria.add(Restrictions.in("setStatus", collection)); //增加条件  1开机 2关机 100离线
     //   detachedCriteria.add(Restrictions.not(Restrictions.in("setStatus", collection))); //增加条件 不等于100  1 - 6 开机 0关机 100离线

        detachedCriteria.addOrder(Order.asc("setStatus")); //根据传入的字段进行升序排序
        pageBean.setDetachedCriteria(detachedCriteria);
        pageQuerDao.pageQuery(pageBean);

        List<SetUnit> rows1 = pageBean.getRows();
        //     System.out.println(pageBean.getRows().size());
        List<BigDateBean> bigDateBeans = new ArrayList<>();
        ObjectMapper mapper = new ObjectMapper();

        BigUnitBean bigUnitBean_json;

        String uuid;


        for (SetUnit setUnit : rows1) {

            BigDateBean bigDateBean = new BigDateBean();//设备实时数据对象


            uuid = setUnit.getSetUuid();
            String json = null; //查询缓存
            try {
                json = (String) jedisClient.get(StringStatic.REDIS_UNIT + uuid);
            } catch (Exception e) {
                e.printStackTrace();
                return ZhongkaiResult.build(500, "redis连接获取失败");
            }

            //System.out.println(json+"getUnitBigDate");
            if (!StringUtils.isNullOrEmpty(json)) {
                bigUnitBean_json = mapper.readValue(json, BigUnitBean.class);
/*
                if (setUnit.getSetStatus() == 100) {
                    bigDateBean.setState("100");//设备状态 从redis中获取
                }else {
                    bigDateBean.setState(bigUnitBean_json.getState());//设备状态 从redis中获取

                }*/


                bigDateBean.setState(String.valueOf(setUnit.getSetStatus()));//设备状态 从redis中获取

                bigDateBean.setUser_name(setUnit.getUserName());//用户姓名 设备表中获取

                bigDateBean.setUnit_ip(setUnit.getSetIp());//设备ip地址 设备表中获取

                bigDateBean.setSignal(bigUnitBean_json.getSignal());//信号强度 从redis中获取


                bigDateBean.setPower(bigUnitBean_json.getPower()); //实时电压

                bigDateBean.setForce(bigUnitBean_json.getForce()); //实时电量

                bigDateBean.setPower_all(bigUnitBean_json.getPower_all());//总耗电量 设备表中获取

                bigDateBean.setUser_t(bigUnitBean_json.getUser_t());//设备设定温度 从redis中获取

                bigDateBean.setAddress_all(setUnit.getAppAddressAll());//设备完整地址 设备表中获取

                bigDateBean.setUnit_uuid(uuid);//设备uuid  设备表中获取

                bigDateBean.setUser_uuid(setUnit.getUserUuid());//用户uuid

                bigDateBean.setSetAlias(setUnit.getSetAlias()); //设备别名

            } else {

               // deviceOperationService.deviceDown2(uuid); //设备下线
                bigDateBean.setState("100");
             //   bigDateBean.setState(setUnit.getSetStatus().toString()); //获取设备数库中的值

                bigDateBean.setUser_name(setUnit.getUserName());//用户姓名 设备表中获取

                bigDateBean.setUnit_ip(setUnit.getSetIp());//设备ip地址 设备表中获取

                bigDateBean.setPower_all(setUnit.getBattery().toString());//总耗电量 设备表中获取

                bigDateBean.setAddress_all(setUnit.getAppAddressAll());//设备完整地址 设备表中获取

                bigDateBean.setUnit_uuid(uuid);//设备uuid  设备表中获取

                bigDateBean.setUser_uuid(setUnit.getUserUuid());//用户uuid
                bigDateBean.setSetAlias(setUnit.getSetAlias()); //设备别名
            }


            bigDateBeans.add(bigDateBean);
            bigDateBean = null;
        }


        pageBean.setRows(bigDateBeans);
        return ZhongkaiResult.ok(pageBean);

    }


    /**
     * 获取大数据页面基本信息
     */
    @Override
    public ZhongkaiResult getUnitBasic() throws Exception {

        BigBaseBean bigBaseBean = new BigBaseBean();

        //SetUnit
        //  DetachedCriteria detachedCriteria = DetachedCriteria.forClass(SetUnit.class);  and su.setBound='2'
        Long aLong = (Long) iBaseDao.get("select count(su) from SetUnit su where su.setRemove='1'");//未被删除的设备数量

        Long normal = (Long) iBaseDao.get("select count(su) from SetUnit su where su.warning=0 and su.setRemove='1'");//正常设备数量

        Long anomaly = (Long) iBaseDao.get("select count(su) from SetUnit su where su.warning!=0 and su.setRemove='1'");//异常设备数量

        Long be = (Long) iBaseDao.get("select count(su) from SetUnit su where su.setStatus!=100 and su.setRemove='1'");//在线设备

        Long start = (Long) iBaseDao.get("select count(su) from SetUnit su where su.setStatus!=0 and su.setStatus!=100 and su.setRemove='1'");//在线并且开机设备

        Long energy = (Long) iBaseDao.get("select count(su) from SetUnit su where su.setStatus!=100 and su.setStatus!=0 and su.setRemove='1' and su.energy>18 and su.energy<30");//在线并且开机节能设备

/*        Long count2 = (Long) iBaseDao.count("select count(su) from SetUnit su where su.setStatus!=100 and su.setStatus!=0 and su.setRemove='1' and su.energy>18 and su.energy<30");

        System.out.println(energy);
        System.out.println(count2);*/

        Long trusteeship = (Long) iBaseDao.get("select count(su) from SetUnit su where su.trusteeship='2' and su.setRemove='1'");//已托管设备

        bigBaseBean.setUnit_all(aLong);  //设备总量
        bigBaseBean.setService_day(ConstantBean.getRunTime()); //设备运行天数


/*        System.out.println(aLong);
        System.out.println(normal);
        System.out.println(anomaly);
        System.out.println(be);
        System.out.println(start);
        System.out.println(trusteeship);*/

       // System.out.println(normal);
        //System.out.println(anomaly);
        bigBaseBean.setNormal_unit(normal.intValue()); //正常设备数量

        bigBaseBean.setAnomaly_unit(anomaly.intValue()); //异常设备数量

/*        DecimalFormat df = new DecimalFormat(".0");//设置保留位数

        String format = df.format(be / aLong );

        String start_count = df.format(start / aLong);

        String trusteeship_count = df.format(trusteeship / aLong);*/
        bigBaseBean.setRatio(divi( String.valueOf(anomaly), String.valueOf(aLong),3)); //异常设备比例

        bigBaseBean.setUnit_be(divi(String.valueOf(be), String.valueOf(aLong), 3)); //设备在线比例
        bigBaseBean.setUnit_be_int(String.valueOf(be)); //在线数量

        bigBaseBean.setUnit_start(divi(String.valueOf(start), String.valueOf(aLong), 3));//设备开机比率
        bigBaseBean.setUnit_start_int(String.valueOf(start));//开机数量

        bigBaseBean.setUnit_save(divi(String.valueOf(energy), String.valueOf(aLong), 3));//在线并且开机节能设备
        bigBaseBean.setUnit_save_int((String.valueOf(energy)));//节能数量

        bigBaseBean.setUnit_trusteeship(divi(String.valueOf(trusteeship), String.valueOf(aLong), 3));//已托管设备
        bigBaseBean.setUnit_trusteeship_int(String.valueOf(trusteeship));//已托管设备数量
        return ZhongkaiResult.ok(bigBaseBean);
    }


    /**
     * 获取页面分析数据
     */
    @Override
    public ZhongkaiResult getUnitAnalyze() throws Exception {
        BigAnalystBean bigAnalystBean = new BigAnalystBean();


        DetachedCriteria detachedCriteria = DetachedCriteria.forClass(Unlike.class);  //异常原因查询
        ProjectionList projectionList = Projections.projectionList();


        projectionList.add(Projections.groupProperty("warCause")); //需要统计的字段

        projectionList.add(Projections.rowCount());
        detachedCriteria.setProjection(projectionList);

        List<Object[]> list = pageQuerDao.pageMax2(detachedCriteria);

        List<BigAnalystBean.CallPoint> callPoints = new ArrayList<>();


        for (Object[] objects : list) {

            BigAnalystBean.CallPoint callPoint = new BigAnalystBean.CallPoint();


            callPoint.setPoint_name(objects[0].toString());
            callPoint.setPoint_count(objects[1].toString());

            callPoints.add(callPoint);

            callPoint = null;
        }


        bigAnalystBean.setCallPoints(callPoints);//异常原因数据格式化

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////


        DetachedCriteria detachedCriteria2 = DetachedCriteria.forClass(SetUnit.class);  //地区分布查询
        detachedCriteria2.add(Restrictions.eq("setRemove", "1")); //增加条件
        detachedCriteria2.add(Restrictions.eq("setBound", "2")); //增加条件 是否绑定业主  1 未绑定 2 已绑定

        //   projectionList.add(Projections.groupProperty(""));


        List<Object[]> appProvince = getJhDate(detachedCriteria2, "appProvince");//地区的条数

        List<BigAnalystBean.Area> areas = new ArrayList<>(); //创建数据容器 接收查询结果

        List<BigAnalystBean.Temperature> temperatures = new ArrayList<>();

        List<BigAnalystBean.MonthKw> monthKws = new ArrayList<>(); //地区耗电量统计

        Collection collection = new ArrayList();

        Long number;
        for (Object[] objects : appProvince) {

            BigAnalystBean.Area area = new BigAnalystBean.Area();//地区分部bean

            Province province = (Province) iBaseDao.get("from Province pr where pr.provinceId='" + objects[0].toString() + "'");

            //  Indent indent = (Indent) iBaseDao.get("from Indent ind where ind.id='" + id + "'");

            area.setArea_name(province.getName());
            area.setArea_count(objects[1].toString());

            areas.add(area);

            area = null;


            //-------------------------------------------

            BigAnalystBean.MonthKw month = new BigAnalystBean.MonthKw();


            List<Long> objects1 = iBaseDao.find("select battery from SetUnit se where se.appProvince='" + objects[0].toString() + "'");


            month.setRegion(province.getName()); //设置地区名称

            number = 0l;

            for (Long objects2 : objects1) {

                //System.out.println(objects2);

                number = number + objects2;
            }


            month.setNumber(String.valueOf(number)); //地区用电总量

            monthKws.add(month);
            //SetUnit

            month = null;



            //---------------------------------------------


            BigAnalystBean.Temperature temperature = new BigAnalystBean.Temperature();//节能模式统计 同样需要地区的数据

            DetachedCriteria detachedCriteria3 = DetachedCriteria.forClass(SetUnit.class);  //地区分布查询
            detachedCriteria3.add(Restrictions.eq("setRemove", "1")); //增加条件
            detachedCriteria2.add(Restrictions.eq("setBound", "2")); //增加条件 是否绑定业主  1 未绑定 2 已绑定
            detachedCriteria3.add(Restrictions.eq("appProvince", objects[0].toString())); //增加条件
            //  detachedCriteria3.add(); //增加条件  小于19度  或者大于29度
            detachedCriteria3.add(Restrictions.or(Restrictions.lt("energy", 19), Restrictions.gt("energy", 29))); //增加条件 //查询一个地区压缩机模式设备的数量
            Long cool_hot = getCount(detachedCriteria3);

            /////////////////////////////
            Long count2 = (Long) iBaseDao.count("select count(su) from SetUnit su where su.appProvince=" + objects[0].toString() + " and su.energy<30 and su.energy>18 ");



          //  System.out.println("and" + count2);
            temperature.setRegion(province.getName()); //地区名称

            temperature.setCool_hot(String.valueOf(cool_hot));

            temperature.setReduction(String.valueOf(count2));


            temperatures.add(temperature); //把此地区数据添加到集合中

            temperature = null;
            //System.out.println(count1+"energy");


            //-----------------------------


        }


        bigAnalystBean.setAreas(areas);

        bigAnalystBean.setTemperatures(temperatures);//节能模式统计全部数据

        bigAnalystBean.setMonthKws(monthKws);


        return ZhongkaiResult.ok(bigAnalystBean);
    }


    /**
     * 获取设备分布数据
     */

    @Override
    public ZhongkaiResult getUnitDis() throws Exception {
        //SetUnit
        //BigUnit_jw


        List<Object[]> list = iBaseDao.find("select longitude,latitude,appAddressAll,userName,userPhone,warning,setStatus from SetUnit se where se.setBound='2'");

        List<BigUnit_jw> bigUnit_jws = new ArrayList<>();

        //System.out.println(list);

        for (Object[] objects : list) {

            try {
                BigUnit_jw jw = new BigUnit_jw();

                jw.setCoords(objects[0].toString() + "," + objects[1].toString());
                jw.setAddress(objects[2].toString());
                jw.setUserName(objects[3].toString());
                jw.setUserPhone(objects[4].toString());
                jw.setWarning(objects[5].toString());
                jw.setStatus(objects[6].toString());

                bigUnit_jws.add(jw);
                jw = null;
            } catch (Exception e) {
                e.printStackTrace();
                continue;
            }
        }


        return ZhongkaiResult.ok(bigUnit_jws);
    }


    public List<Object[]> getJhDate(DetachedCriteria detachedCriteria, String name) {
        ProjectionList projectionList = Projections.projectionList();


        projectionList.add(Projections.groupProperty(name));
        projectionList.add(Projections.rowCount());
        detachedCriteria.setProjection(projectionList);

        List<Object[]> list = pageQuerDao.pageMax2(detachedCriteria);

        return list;
    }

    public Long getCount(DetachedCriteria detachedCriteria) {
        ProjectionList projectionList = Projections.projectionList();


        //projectionList.add(Projections.groupProperty(name));
        projectionList.add(Projections.rowCount());
        detachedCriteria.setProjection(projectionList);

        Long count = pageQuerDao.getCount(detachedCriteria);

        return count;
    }


    public String divi(String num1, String nums, int len) {
        BigDecimal first = new BigDecimal(num1);
        BigDecimal second = new BigDecimal(nums);
        return first.divide(second, len, BigDecimal.ROUND_HALF_UP).toString();
    }
}
